package cn.uin.domain.family.service;

import cn.uin.domain.family.adapter.port.IFamilyNotificationPort;
import cn.uin.domain.family.adapter.repository.IFamilyRepository;
import cn.uin.domain.family.model.aggregate.UserFamilyInfoAggregate;
import cn.uin.domain.family.model.entity.HomeFamilyEntity;
import cn.uin.domain.family.model.entity.HomeFamilyListEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName FamilyService
 * @Description:家庭服务实现
 * @Author: Administrator
 * @CreateDate: 2025/11/11 15:38
 * @Version: 1.0
 */
@Slf4j
@Service
public class FamilyService implements IFamilyService{

	@Resource
	private IFamilyRepository iFamilyRepository;

	@Resource
	private IFamilyNotificationPort iFamilyNotificationPort;

	@Override
	public UserFamilyInfoAggregate queryUserFamilyInfo(Long userId) {
		HomeFamilyListEntity homeFamilyListEntities = iFamilyRepository.queryFamilyListByUserId(userId);
		if (ObjectUtils.isEmpty(homeFamilyListEntities)) return null;

		HomeFamilyEntity homeFamilyEntity = iFamilyRepository.queryFamilyById(homeFamilyListEntities.getFamilyId());
		List<HomeFamilyListEntity> homeFamilyLists = iFamilyRepository.queryOtherFamilyList(userId);

		return UserFamilyInfoAggregate.builder()
				.homeFamilyEntity(homeFamilyEntity)
				.currentUserHomeFamilyListEntity(homeFamilyListEntities)
				.homeFamilyListsEntity(homeFamilyLists)
				.build();
	}

	@Override
	public String activateAddFamily(String token, String email, Long familyId, RedirectAttributes redirectAttributes, Model model) {
		return iFamilyRepository.checkTokenAndActivateAddFamily(token, email, familyId, redirectAttributes, model);
	}

	@Override
	public Boolean inviteToFamily(Long family, String email) {
		return iFamilyNotificationPort.sendEmailLink(family, email);
	}

	@Override
	public void createFamily(HomeFamilyEntity homeFamilyEntity) {
		iFamilyRepository.insert(homeFamilyEntity);
	}
}
